package com.wangjiacai.utils.web.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangjiacai.utils.web.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Service
@ConditionalOnProperty(value = "wangjiacai.redis",havingValue = "memory")
public class MemoryRedisService implements RedisService {

    private ConcurrentHashMap<String,String> cache = new ConcurrentHashMap();

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void set(String key, Object value) {
        try {
            cache.put(key, objectMapper.writeValueAsString(value));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void set(String key, String value) {
        cache.put(key, value);
    }

    @Override
    public void set(String key, Object value, long expireTime) {

    }

    @Override
    public void set(String key, String value, long expireTime) {

    }

    @Override
    public void hashSet(String key, Object hk, Object value) {

    }

    @Override
    public boolean exists(String key) {
        return cache.contains(key);
    }

    @Override
    public <T> T get(String key, Class<T> clazz) {
        String s = get(key);
        if (s == null) return null;
        try {
            return objectMapper.readValue(s,clazz);
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public <T> T hashGet(String key, Object hk, Class<T> clazz) {
        return null;
    }

    @Override
    public String get(String key) {
        if(key==null) return null;
        return cache.get(key);
    }

    @Override
    public String hashGet(String key, Object hk) {
        return null;
    }

    @Override
    public boolean delete(String key) {
        cache.remove(key);
        return true;
    }

    @Override
    public long hashDelete(String key, Object hk) {
        return 0;
    }

    @Override
    public int getExpire() {
        return 0;
    }
}
